<?php
namespace app\admin\controller;
use think\Db;
class User extends Base
{
    //列表
    public function lists()
    {
        if(is_post()){
            $is_down = input('is_down');
            $cur_page     = input('page');
            $level = input('level');
            $search_type = input('search_type');
            $status  = input('status');
            $px_type  = input('px_type');
            $is_activate  = input('is_activate');
            $is_businessman  = input('is_businessman');
            $keyword  = input('keyword');
            $min_time = input('min_time');
            $max_time = input('max_time');
            $sql = "
            select
                [1]
            from
                user
            ";
            $param = [];
            $w = ['where'];
            if ($level != '100all') {
                $w[] = ' and level = ?';
                $param[] = $level;
            }
            if ($status != '100all') {
                $w[] = ' and status = ?';
                $param[] = $status;
            }
            if ($is_activate != '100all') {
                $w[] = ' and is_activate = ?';
                $param[] = $is_activate;
            }
            if ($is_businessman != '100all') {
                $w[] = ' and is_businessman = ?';
                $param[] = $is_businessman;
            }
            if(!empty($min_time)){
                $w[] = ' and create_time>?';
                $param[] = strtotime($min_time);
            }
            if(!empty($max_time)){
                $w[] = ' and create_time<?';
                $param[] = strtotime($max_time);
            }
            if ($search_type!='100all'){
                if (! empty($keyword)) {
                    switch ($search_type) {
                        case 'user_no':
                            $w[] = ' and user_no like ?';
                            $param[] = "%{$keyword}%";
                        break;
                        case 'name':
                            $w[] = ' and name like ?';
                            $param[] = "%{$keyword}%";
                        break;
                        case 'phone':
                            $w[] = ' and phone like ?';
                            $param[] = "%{$keyword}%";
                        break;
                        case 'idcard':
                            $w[] = ' and idcard like ?';
                            $param[] = "%{$keyword}%";
                        break;
                    }
                }
            }

            #条件判断
            if (count($w)>1){
              $w[1] = str_replace("and","",$w[1]);
              $sql .= implode(" ",$w);
            }

            //汇总
            $d = [
                ["总人数","count(*) as nums", ""],
                ["激活数","count(*) as nums", " and is_activate=1"],
                ["未激活","count(*) as nums", " and is_activate=0"],
                ["开启","count(*) as nums", " and status=0"],
                ["冻结","count(*) as nums", " and status=1"],
                ["居间商","count(*) as nums", " and is_businessman=1"],
                ["报单金额","sum(baodan_money) as nums", ""],
                ["回馈积分","sum(hk_money) as nums", ""],
                ["注册积分","sum(zc_money) as nums", ""],
                ["冻结积分","sum(dj_money) as nums", ""],
                ["重消积分","sum(cx_money) as nums", ""],
                ["复投积分","sum(ft_money) as nums", ""],
                ["增值积分","sum(zz_money) as nums", ""],
            ];
            $count_html = com_list_count($sql, $param,$d);

            #分页
            $page_size = c('a.page_size');
            $page_html = com_list_page($sql, $param, $cur_page,$page_size);

            #内容
            $start = ($cur_page - 1) * $page_size;
            $field = "id,user_no,name,phone,is_activate,is_businessman,
            baodan_money,hk_money,zc_money,dj_money,cx_money,ft_money,zz_money,
            level,status,s_nums,create_time";
            $sql_list = str_replace("[1]",$field,$sql);

            if ($is_down) {
                $sql_list .= " order by id desc";
            }else{
                if ($px_type!='100all'){
                    if ($px_type=='s_nums') {
                        $sql_list .= " order by s_nums desc limit $start, $page_size";
                    }else{
                        $sql_list .= " order by {$px_type} desc limit $start, $page_size";
                    }
                }else{
                    $sql_list .= " order by id desc limit {$start},{$page_size}";
                }
            }

            $rslist = Db::query($sql_list, $param);
            foreach ($rslist as $k => $v) {
                $rslist[$k]['level'] = c('type.level',$v['level']);
                $rslist[$k]['status'] = c('type.status',$v['status']);
                $rslist[$k]['is_activate'] = c('type.is_activate',$v['is_activate']);
                $rslist[$k]['is_businessman'] = c('type.is_businessman',$v['is_businessman']);
                $rslist[$k]['create_time'] = com_formate_time($v['create_time']);
                $rslist[$k]['action']  = com_btn_edit("/user/detail/id/{$v['id']}",'','','详情');
                $rslist[$k]['action'] .= com_btn_edit("/user/edit/id/{$v['id']}");
                $rslist[$k]['action'] .= com_btn_edit("/user/editMoney/id/{$v['id']}",'','','资金变动');
            }
            if($is_down){
                $url = com_down_csv($rslist,
                ['ID','编号','姓名','手机号','级别','是否激活','居间商','报单金额','回馈积分','注册积分','冻结积分','重消积分','复投积分','增值积分','状态','推荐数','时间'],
                ['id','user_no','name','phone','level','is_activate','is_businessman','baodan_money','hk_money','zc_money','dj_money','cx_money','ft_money','zz_money','status','s_nums','create_time'],'user','xls');
                com_check(['data'=>$url,'suc_js'=>'function.openurl']);
            }
            $body_html = com_list_body($rslist, ['id','user_no','name','phone','level','is_activate','is_businessman','baodan_money','hk_money','zc_money','dj_money','cx_money','ft_money','zz_money','status','s_nums','create_time','action']);
            com_check(['data'=>['com_body'=>$body_html, 'com_page'=>$page_html,'com_count'=>$count_html]]);
        }
        $d = [
            'level' => ['100all'=>'全部级别'] + c('type.level'),
            'status' => ['100all'=>'全部状态'] + c('type.status'),
            'is_activate' => ['100all'=>'是否激活'] + c('type.is_activate'),
            'is_businessman' => ['100all'=>'居间商'] + c('type.is_businessman'),
            'px_type' => ['100all' => '排序类型','s_nums'=>'推荐数']+c('type.money_type'),
        ];
        return view('',$d);
    }

    //市场列表
    public function slists($id='')
    {
        if (is_post()) {
            $cur_page = input('page');
            $keyword  = input('keyword');
            $status  = input('status');
            $id  = input('id');
            $min_time = input('min_time');
            $max_time = input('max_time');

            // 原生态sql查询
            $sql = "
                select
                    [1]
                from
                    user
            ";
            $param = [];
            $w = ['where'];
            $w[] = ' and s_id=?';
            $param[] = $id;

            if (! empty($keyword)) {
                $w[] = " and (user_no like ? or name like ? or phone like ?)";
                $param[] = "%{$keyword}%";
                $param[] = "%{$keyword}%";
                $param[] = "%{$keyword}%";
            }
            if ( $status != '100all' ) {
                $w[] = " and status = ?";
                $param[] = $status;
            }
            if (! empty($min_time)) {
                $w[] = " and create_time >= ?";
                $param[] = strtotime($min_time);
            }
            if (! empty($max_time)) {
                $w[] = " and create_time <= ?";
                $param[] = strtotime($max_time);
            }

            #条件判断
            if (count($w)>1){
              $w[1] = str_replace("and","",$w[1]);
              $sql .= implode(" ",$w);
            }
            #分页
            $page_size = c('a.page_size');
            $page_html = com_list_page($sql, $param, $cur_page,$page_size);

            #内容
            $start = ($cur_page - 1) * $page_size;
            $field = "id,user_no,name,phone,status,create_time,s_tree ";
            $sql_list = str_replace("[1]",$field,$sql);
            $sql_list .= " order by id desc limit {$start},{$page_size}";
            $rslist = Db::query($sql_list, $param);

            $c = new \app\index\model\Check();
            // 格式数据
            foreach ($rslist as $k => $v) {
                $rslist[$k]['create_time'] = com_formate_time($v['create_time']);

                $rslist[$k]['status']      = c('type.status',$v['status']);
                $count = $c->getTeamYeji($v['id'],$v['s_tree']);
                $rslist[$k]['yeji']        = number_format($count,2);
            }
            $body_html = com_list_body($rslist, ["user_no",
                "name",
                "phone",
                "yeji",
                "status",
                "create_time",]);
            com_check(['data'=>['com_body'=>$body_html, 'com_page'=>$page_html]]);
        }
        $data = [
            'id'      => $id,
            'status'  => ['100all'=>'全部状态'] + c('type.status'),
        ];
        return view('', $data);
    }

    //市场列表
    public function tlists($id='')
    {
        if (is_post()) {
            $cur_page = input('page');
            $keyword  = input('keyword');
            $status  = input('status');
            $id  = input('id');
            $min_time = input('min_time');
            $max_time = input('max_time');

            // 原生态sql查询
            $sql = "
                select
                    [1]
                from
                    user
            ";
            $param = [];
            $w = ['where'];
            $w[] = ' and s_tree like ?';
            $param[] = Db::name('user')->where('id',$id)->value('s_tree').$id.',%';

            if (! empty($keyword)) {
                $w[] = " and (user_no like ? or name like ? or phone like ?)";
                $param[] = "%{$keyword}%";
                $param[] = "%{$keyword}%";
                $param[] = "%{$keyword}%";
            }
            if ( $status != '100all' ) {
                $w[] = " and status = ?";
                $param[] = $status;
            }
            if (! empty($min_time)) {
                $w[] = " and create_time >= ?";
                $param[] = strtotime($min_time);
            }
            if (! empty($max_time)) {
                $w[] = " and create_time <= ?";
                $param[] = strtotime($max_time);
            }

            #条件判断
            if (count($w)>1){
              $w[1] = str_replace("and","",$w[1]);
              $sql .= implode(" ",$w);
            }
            #分页
            $page_size = c('a.page_size');
            $page_html = com_list_page($sql, $param, $cur_page,$page_size);

            #内容
            $start = ($cur_page - 1) * $page_size;
            $field = "id,user_no,name,phone,status,create_time,s_tree ";
            $sql_list = str_replace("[1]",$field,$sql);
            $sql_list .= " order by id desc limit {$start},{$page_size}";
            $rslist = Db::query($sql_list, $param);

            $c = new \app\index\model\Check();
            // 格式数据
            foreach ($rslist as $k => $v) {
                $rslist[$k]['create_time'] = com_formate_time($v['create_time']);

                $rslist[$k]['status']      = c('type.status',$v['status']);
                $count = $c->getTeamYeji($v['id'],$v['s_tree']);
                $rslist[$k]['yeji']        = number_format($count,2);
            }
            $body_html = com_list_body($rslist, ["user_no",
                "name",
                "phone",
                "yeji",
                "status",
                "create_time",]);
            com_check(['data'=>['com_body'=>$body_html, 'com_page'=>$page_html]]);
        }
        $data = [
            'id'      => $id,
            'status'  => ['100all'=>'全部状态'] + c('type.status'),
        ];
        return view('', $data);
    }

    public function detail($id=''){
        $sql = "
                SELECT
                    a.*,b.name as usname,b.user_no as us_no,c.name as regname
                FROM
                    user a
                left join
                    user b
                on
                    a.s_id = b.id
                left join
                    user c
                on
                    a.reg_id = c.id
                WHERE
                    a.id = ?
            ";
        $rs = Db::query($sql, [
            $id
        ]);
        $c = new \app\index\model\Check();
        $data = [
            'info' => $rs[0],
            'yeji' => $c->getTeamYeji($id,$rs[0]['s_tree']),
            'newadd' => $c->getNewAddYeji($id,$rs[0]['s_tree']),
            'award' => $c->getAward($id),
        ];
        return view('',$data);
    }

    /*
        修改金额
     */
    public function editMoney($id=''){
        if (is_post()) {
            $d = input();
            $rule = [
                'money'         =>  'require|float',
                'money_type'    =>  'require',
                'note'          =>  'require',
            ];
            $msg = [
                'money.require' =>'金额不能为空',
                'note.require'  =>'请填写备注信息',
                'money.float'   =>'金额格式不对',
            ];
            com_validate( $rule, $msg, $d, true );
            $o = new \app\admin\model\Orderumoney();
            $o->doit($id, $this->userinfo['id'], $d['money_type'], $d['money'], $d['note']);
            //log
            $l = new \app\common\model\Log();
            $money_type = c('type.money_type',$d['money_type']);
            $l->admin('变动会员资金['.$money_type.']=>['.$d['money'].']',$id);

            $config = [
                'suc_msg' => '资金变动成功',
                'suc_js' => 'alert|close|f5',
            ];
            com_check( $config );
        }
        //模板赋值
        $info = Db::name("user")->field('id,name,phone,baodan_money,hk_money,zc_money,dj_money,cx_money,ft_money,zz_money,stock_zz_money,max_money')->find($id);
        $money_type = c('type.money_type');
        unset($money_type['zz_money']);
        unset($money_type['award_fl']);
        unset($money_type['award_fx']);
        unset($money_type['award_fw']);
        unset($money_type['award_gl']);
        $data = [
            'info'      => $info,
            'money_type'=> $money_type
        ];
        return view('', $data);
    }


    public function edit($id=''){
        $rs = Db::name('user')->find($id);
        if(is_post()){
            $d = post();
            $rule = [
                'name'   =>  'require',
                'phone'   =>  'require|regex:/^1[34578]{1}\d{9}$/',
                //'idcard' =>  'require|unique:user,idcard,'.$id.',id',
            ];
            $msg = [
              'name.require'   =>  '请输入姓名',
              'phone.require'  =>  '请输入手机号',
              'phone.regex'    =>  '手机格式不对',
              //'phone.unique'    =>  '该手机号已经存在',
              //'idcard.require' =>  '请输入身份证',
              //'idcard.unique' =>  '该身份证已存在',
            ];
            com_validate($rule, $msg, $d);
            if ( !empty($d['pwd']) ) {
                $d['pwd'] = com_password($d['pwd']);
            }else{
                unset($d['pwd']);
            }
            if ( !empty($d['s_pwd']) ) {
                $d['s_pwd'] = com_password($d['s_pwd']);
            }else{
                unset($d['s_pwd']);
            }
            // if (!empty($d['idcard'])) {
            //     #身份证号码
            //     $o = new \org\Idcard();
            //     if(!$o->init($d['idcard'])){
            //         com_error('请填写正确的身份证号码!','idcard');
            //         com_check();
            //     }
            // }
            unset($d['user_no']);
            $d['update_time'] = time();
            #log
            $l = new \app\common\model\Log();
            if ($rs['name']!=$d['name']) { $l->admin('修改会员姓名['.$rs['name'].']=>['.$d['name'].']',$d['id']); }
            if ($rs['level']!=$d['level']) { $l->admin('修改会员级别['.c('type.level',$rs['level']).']=>['.c('type.level',$d['level']).']',$d['id']); }
            if ($rs['status']!=$d['status']) { $l->admin('修改会员登陆状态['.c('type.status',$rs['status']).']=>['.c('type.status',$d['status']).']',$d['id']); }
            if ($rs['is_activate']!=$d['is_activate']) { $l->admin('修改会员激活状态['.c('type.is_activate',$rs['is_activate']).']=>['.c('type.is_activate',$d['is_activate']).']',$d['id']); }
            if ($rs['is_businessman']!=$d['is_businessman']) { $l->admin('修改会员居间商状态['.c('type.is_businessman',$rs['is_businessman']).']=>['.c('type.is_businessman',$d['is_businessman']).']',$d['id']); }
            if ($rs['is_send_award']!=$d['is_send_award']) { $l->admin('修改会员发奖状态['.c('type.is_send_award',$rs['is_send_award']).']=>['.c('type.is_send_award',$d['is_send_award']).']',$d['id']); }
            //if ($rs['phone']!=$d['phone']) { $l->admin('修改会员手机号['.$rs['phone'].']=>['.$d['phone'].']',$d['id']); }
            //if ($rs['idcard']!=$d['idcard']) { $l->admin('修改会员身份证['.$rs['idcard'].']=>['.$d['idcard'].']',$d['id']); }
            // if ($rs['fl_config']!=$d['fl_config']) { $l->admin('修改会员返利配置['.$rs['fl_config'].']=>['.$d['fl_config'].']',$d['id']); }
            // if ($rs['fx_config']!=$d['fx_config']) { $l->admin('修改会员分享配置['.$rs['fx_config'].']=>['.$d['fx_config'].']',$d['id']); }
            // if ($rs['fw_config']!=$d['fw_config']) { $l->admin('修改会员服务配置['.$rs['fw_config'].']=>['.$d['fw_config'].']',$d['id']); }
            // if ($rs['gl_config']!=$d['gl_config']) { $l->admin('修改会员管理配置['.$rs['gl_config'].']=>['.$d['gl_config'].']',$d['id']); }
            if ($rs['is_mtom']!=$d['is_mtom']) { $l->admin('修改会员转账权限['.c('type.user_is_mtom',$rs['is_mtom']).']=>['.c('type.user_is_mtom',$d['is_mtom']).']',$d['id']); }
            if ($rs['max_money']!=$d['max_money']) { $l->admin('修改会员转账权限['.$rs['is_mtom'].']=>['.$d['is_mtom'].']',$d['id']); }


            //配置
            // foreach(['fl_config','fx_config','fw_config','gl_config'] as $key){
            //     $v = explode(",",$d[$key]);
            //     $one = (int)$v[0];
            //     $one = $one>100?100:($one<0?0:$one);
            //     $two = 100-$one;
            //     $d[$key] = implode(",",[$one,$two]);
            // }
            Db::name("user")->update($d);
            com_check(['suc_msg'=>'修改成功!','suc_js'=>'alert|close|reload']);
        }
        $data = [
            'info' => $rs,
            'level' => c('type.level'),
            'status' => c('type.status'),
            'is_activate' => c('type.is_activate'),
            'is_businessman' => c('type.is_businessman'),
            'is_send_award' => c('type.is_send_award'),
            'is_mtom' => c('type.user_is_mtom'),
        ];
        return view('',$data);
    }

    /**
     * 修改推荐人
     * @return [type] [description]
     */
    public function editsid($id=''){
        if (is_post()) {
            $data = input();
            //验证
            $rule = [
                'id'         =>  'require',
                's_id'       =>  'require',
                'user_no'       =>  'require',
            ];
            $msg = [
                'id.require'         =>  '会员错误',
                's_id.require'       =>  '请填写推荐用户',
                'user_no.require'   =>  '请填写推荐用户',
            ];
            com_validate( $rule, $msg, $data, true );
            if ( $data['id'] == 1 ) {
                com_error('系统第一人不能修改','user_no');
                com_check();
            }
            if (Db::name('user')->where('user_no',$data['user_no'])->value('id') != $data['s_id']){
                com_error('推荐用户错误','user_no');
                com_check();
            }

            #用户信息
            $userinfo = Db::name('user')->field('id,s_tree,name,s_id,s_level,user_no')->find($data['id']);

            #推荐人未改
            if ( $data['s_id'] == $userinfo['s_id'] ) {
                $config = ['suc_msg' => '编辑成功！','suc_js' => 'alert|close',];
                com_check( $config );
            }
            #格式数据
            $self_tree = $userinfo['s_tree'].$userinfo['id'].',%';
            $old_s_tree = Db::name('user')->where('id',$userinfo['s_id'])->value('s_tree');
            $b_rs = Db::query("select id from user where s_level>? and s_tree like ?",[$userinfo['s_level'],$self_tree]);
            $b_ids = array_column($b_rs, 'id');
            #推荐编号不能是自己 #推荐编号不能是下级
            if ( $data['s_id'] == $userinfo['id'] || in_array($data['s_id'],$b_ids) ) {
                com_error('推荐用户不能是自己或下级','user_no');
                com_check();
            }
            #修改推荐人
            #新推荐人的tree,level
            $s_tree = Db::name('user')->where('id',$data['s_id'])->value('s_tree');

            Db::startTrans();
            $mysql   = [];
            #修改自己的推荐关系
            $d = [
            'id'     => $userinfo['id'],
            's_id'   => $data['s_id'],
            's_tree' => $s_tree.$data['s_id'].',',
            ];
            $d['s_level'] = count(explode(",", $d['s_tree']))-2;
            if ( $d['s_level'] < 0 ) {
                com_error('推荐用户错误','user_no');
                com_check();
            }
            $mysql[] = Db::name('user')->update($d);

            //记录log
            $note_log = [
                'user_id'     => $userinfo['id'],
                'name'        => $userinfo['user_no'],
                'old_s_id'    => $userinfo['s_id'],
                'new_s_id'    => $data['s_id'],
                'create_time' => time(),
            ];
            $mysql[] = Db::name('tj_history')->insertGetId($note_log);
            //改变的层数
            $add = count(explode(",", $s_tree)) - count(explode(",", $old_s_tree));

            #遍历修改自己推荐下级会员的tree
            if($b_ids){
                $b_ids = implode(",", $b_ids);
                $old_tree = $userinfo['s_tree'].$userinfo['id'].',';
                $new_tree = $s_tree.$data['s_id'].','.$userinfo['id'].',';
                if ( $add >= 0 ) {
                    $mysql[] = Db::execute("update user set s_tree=REPLACE(s_tree,'{$old_tree}','{$new_tree}') ,s_level=s_level+$add  where id in ({$b_ids})");
                }
                if ( $add < 0 ) {
                    $add = abs($add);
                    $mysql[] = Db::execute("update user set s_tree=REPLACE(s_tree,'{$old_tree}','{$new_tree}') ,s_level=s_level-$add  where id in ({$b_ids})");
                }
            }
            $mysql[] = Db::execute("update user set s_nums=s_nums+? where id=?",[1,$data['s_id']]);
            $mysql[] = Db::execute("update user set s_nums=s_nums-? where id=?",[1,$userinfo['s_id']]);
            //log
            $l = new \app\common\model\Log();
            $s_name = Db::name('user')->where('id',$data['s_id'])->value('user_no');
            $l->admin('修改'.$userinfo['name'].'['.$userinfo['user_no'].']的推荐人为['.$s_name.']',$userinfo['id']);
            $check = true;
            foreach($mysql as $v){ if( !$v ){ $check = false; break;} }
            if( $check ){
                Db::commit();
                com_check(['suc_msg' => '编辑成功！','suc_js' => 'alert|close|f5']);
            }else{
                Db::rollback();
                com_check(['err_msg' => '编辑失败！','err_js' => 'alert|close|f5']);
            }
        }
        $info = Db::query("select us.id,us.user_no,us.name from user u left join user us on u.s_id=us.id where u.id=?",[$id]);
        $data = [
            'info' => $info[0],
            'id' => $id
        ];
        return view('',$data);
    }

    public function getInfo(){
        if (is_post()) {
            $user_no = input('user_no');
            $rs = Db::name('user')->field('id,name,user_no')->where('user_no',$user_no)->select();
            if ( !$rs ){
                com_error('用户错误');
                com_check();
            }
            com_check(['data'=>$rs[0]]);
        }
    }

    //释放
    public function release($id='')
    {
        if (is_post()) {

        }
        $data = [
            'id' => $id
        ];
        return view('',$data);
    }

}
